//
//  PzApplePayHelper.swift
//  Pz
//
//  Created by 蓝鳍互娱 on 2024/7/4.
//

import Foundation
import StoreKit
import XHToastSwift
class PzApplePayHelper: NSObject {
    @objc public static var shareManage = PzApplePayHelper()
    var applePayScuessBlock: (() -> Void)?

    var payProductId:String?
    @objc open func startApplePay(productId:String){
        if productId.count > 0{
            payProductId = productId
            
            SKPaymentQueue.default().add(self)
            if SKPaymentQueue.canMakePayments(){
                SVProgressHUD.show(withStatus: "正在支付")
                requestProduct(productId: productId)
            }
        }
    }
    func requestProduct(productId:String){
        let product = [productId]
        let nsset = Set(product)
        let request = SKProductsRequest(productIdentifiers: nsset)
        request.delegate = self
        request.start()
    }
    var payTransaction:SKPaymentTransaction?
    func completeTransaction(transaction:SKPaymentTransaction){
        payTransaction = transaction
        guard let receiptUrl = Bundle.main.appStoreReceiptURL else { return  }
        let receiptData = NSData(contentsOf: receiptUrl)
        let receiptString = receiptData?.base64EncodedString(options:.endLineWithLineFeed)
        let boxUrl = "https://sandbox.itunes.apple.com/verifyReceipt"
        let recUrl = "https://buy.itunes.apple.com/verifyReceipt"
        localReceiptVerUrl(requestUrl: boxUrl, receiptStr: recUrl, transaction: transaction)
        SKPaymentQueue.default().finishTransaction(transaction)
    }
    func finshTransaction(transaction:SKPaymentTransaction){
        payTransaction = transaction
        SVProgressHUD.dismiss()
        SKPaymentQueue.default().finishTransaction(transaction)
    }
    func localReceiptVerUrl(requestUrl:String,receiptStr:String,transaction:SKPaymentTransaction){
        let requestDic = ["receipt-data":receiptStr,"password":"b93e9d9edffb49549cf7a94bd6d1430a","exclude-old-transactions":true] as [String : Any]
        let requestData = try? JSONSerialization.data(withJSONObject: requestDic, options:JSONSerialization.WritingOptions.prettyPrinted)
        let verifyUrlStr = requestUrl
        if let url = URL(string: verifyUrlStr) {
            var request = URLRequest(url: url)
            request.cachePolicy = .useProtocolCachePolicy
            request.timeoutInterval = 10.0
            request.httpMethod = "POST"
            request.httpBody = requestData
            
            let session = URLSession.shared
            let task = session.dataTask(with: request) { (data, response, error) in
                DispatchQueue.main.async {
                    SVProgressHUD.dismiss()
                    
                    if error != nil {
                        print("链接失败")
                        SKPaymentQueue.default().finishTransaction(transaction)
                    } else {
                        do {
                            if let jsonResponse = try JSONSerialization.jsonObject(with: data!, options: []) as? [String: Any] {
                                // 验证成功
                                print("验证成功")
                                
                                // 在主队列执行成功回调
                                DispatchQueue.main.async {
                                    self.applePayScuessBlock?()
                                }
                            } else {
                                // 验证失败
                                print("验证失败")
                                SKPaymentQueue.default().finishTransaction(transaction)
                            }
                        } catch {
                            print("JSON解析错误: \(error)")
                        }
                    }
                }
            }
            task.resume()
        }
    }
}
extension PzApplePayHelper:SKProductsRequestDelegate,SKPaymentTransactionObserver{
    func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
        for i in 0..<transactions.count {
            let tran = transactions[i]
            switch tran.transactionState {
            case .purchased://交易完成
                completeTransaction(transaction: tran)
            case .restored:do {//已经购买过该商品
                SVProgressHUD.dismiss()
                queue.finishTransaction(tran)
                applePayScuessBlock?()
            }
            case .failed://购买失败
                finshTransaction(transaction: tran)
            default: break
                
            }
            
        }
    }
    
    func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) {
        let product = response.products
        if product.count > 0{
            for i in 0..<product.count {
                let pro = product[i]
                if pro.productIdentifier == payProductId{
                    let payment = SKPayment(product: pro)
                    SKPaymentQueue.default().add(payment)
                }
                
            }
        }else{
            DispatchQueue.main.async() {
                SVProgressHUD.dismiss()
                XHToast.showCenterWithText("没有产品")
            }
        }
    }
    func paymentQueue(_ queue: SKPaymentQueue, shouldAddStorePayment payment: SKPayment, for product: SKProduct) -> Bool {
        return true
    }
    func request(_ request: SKRequest, didFailWithError error: Error) {
        DispatchQueue.main.async() {
            SVProgressHUD.dismiss()
            XHToast.showCenterWithText("支付失败")
        }
    }
}
